using System;
using System.Timers;
using TimeToGo.Presentation.ViewModels;
using TimeToGo.Presentation;

namespace TimeToGo.Services
{
    internal class TimeSource : ITimeSource
    {
        public event EventHandler<TimeElapsedEventArgs> TimeElapsed;
        
        private readonly Timer _timer;

        private TimeInfoDecorator _currentTime;
        public TimeInfoDecorator CurrentTime
        {
            get { return _currentTime; }
            set
            {
                _currentTime = value;
                if (_currentTime != null)
                {
                    // fire it once to update the ui imediatly...
                    _timer_Elapsed(this, null);
                    _timer.Start();
                }
                else
                {
                    _timer.Stop();
                }
            }
        }

        public TimeSource()
        {
            _timer = new Timer();
            _timer.Elapsed += _timer_Elapsed;
            _timer.Interval = 1000;
        }

        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            EventHandler<TimeElapsedEventArgs> handler = TimeElapsed;
            if (handler != null)
                handler(this, new TimeElapsedEventArgs(CurrentTime.Time.Subtract(DateTime.Now)));
        }
    }

}